<?php
namespace app\common\model;
use think\Model;
use think\DB;
class User extends Model{
	protected $insert = ['regip','regdate','userpid'];
	protected $auto = ['isRemind', 'isstation','lastdate'];
	protected function setPasswordAttr($value, $data){
		return md5(md5($value).$data['encrypt']);
	}
	protected function setUserpidAttr(){
		return intval(cookie('zanpiancms_register_pid'));
	}	
	protected function setRegdateAttr(){
		return time();
	}
	protected function setLastdateAttr(){
		return time();
	}	
	protected function setRegipAttr(){
		return ip2long(get_client_ip());
	}	
	protected function setNicknameAttr($value,$data){
		if ($value){
			return $value;
		}else{
			return $data['username'];
			}
	}	
	protected function setisRemindAttr($value){		
		return !empty($value)? $value : 0;
	}	
	protected function setisstationAttr($value){
		return !empty($value)? $value : 0;
	}	
	public function getgroupnameAttr(){
		$gbcid = array(0=>'未开启认证注册',1=>'未认证邮箱',2=>'邮箱认证成功');
		return $gbcid;
	}	
	public function detail(){
		return $this->hasOne('UserDetail','userid');
    }
	public function visitors(){
        return $this->hasMany('visitors','visitors_userid');
    }	
	public function comment(){
        return $this->hasMany('cm','cm_uid');
    }
	public function favorite(){
        return $this->hasMany('Favorite','favorite_uid');
    }	
	public function remind(){
        return $this->hasMany('Remind','remind_uid');
    }	
	public function playlog(){
        return $this->hasMany('Playlog','log_uid');
    }
	public function gb(){
        return $this->hasMany('gb','gb_uid');
    }
	public function orders(){
        return $this->hasMany('orders','order_uid');
    }	
	public function msg(){
        return $this->hasMany('msg','msg_uid');
    }
	public function score(){
        return $this->hasMany('score','score_uid');
    }
	public function order(){
        return $this->hasMany('orders','order_uid');
    }		
	public function api(){
        return $this->hasMany('UserApi','uid');
    }
	/**
	 * 第三方绑定查询
	*/
	public function GetApiUser($openid="",$channel=""){
		//$rs=model('UserApi');
		$where['openid']=$openid;
		$user=db('user_api')->alias('a')->join('user u','u.userid=a.uid')->join('user_detail d','d.userid=a.uid')->where($where)->find();
		//$user = $rs->relation('user,detail')->where($where)->find();
		if($user['userid']){
		  if($user['islock']==1){
				$this->error('用户被禁用');
		  }
		  $this->autoLogin($user);//更新登录信息
		  return $user;	
		}else{
		  return false;		
		}
		
	}		
	/**
	 * 修改用户资料
	 */
	public function editUser($data, $ischangepwd = false){
		$rs=model('User');
		if ($data['userid']) {
			if (!$ischangepwd || ($ischangepwd && $data['password'] == '')) {
				unset($data['encrypt']);
				unset($data['password']);
			}else{
				$data['encrypt'] = rand_string(6);
			}
			$rs->save($data, array('userid'=>$data['userid']));
            if($rs->detail->userid){
			$rs->detail->save($data);
			}else{
			$rs->detail()->save($data);	
			}
			return $rs->userid;
		}else{
			$this->error = "非法操作！";
			return false;
		}
	}	
	//获取用户资料
	public function getuserinfo($userid=""){
		if(!$userid){ return false; }
		$user = $this->withCount('comment,favorite,remind,playlog,gb,msg,score,order')->relation('detail,api')->where('userid',$userid)->find();
		if($user){
			return $user;
		}else{
		    return false;
		}
	}
	/**
	 * 用户注册
	 */
	public function reg($username='',$email='',$password='',$isautologin = true){
		$userconfig=F('_data/userconfig_cache');
		$user_api=session('user_auth_api');
		$data['username']=!empty($username) ? $username : rand_string(6);
		$data['nickname'] = !empty($user_api['nickname']) ? $user_api['nickname'] : $username;
		$data['encrypt'] = rand_string(6);
		$data['email']=$email;
		$data['password']=$password;
		$data['regdate'] = time();
		$data['lastdate'] = time();
		$data['regip'] = get_client_ip();
		$data['loginnum'] = 0;
		$data['islock'] = 0;
		if(!empty($user_api['openid'])){
		$data['channel'] = !empty($user_api['channel']) ? $user_api['channel'] : "";
		$data['openid'] = !empty($user_api['openid']) ? $user_api['openid'] : "";
		$data['avatar'] = !empty($user_api['avatar']) ? $user_api['avatar'] : "";
		$data['sex'] = !empty($user_api['sex']) ? $user_api['sex'] : "";
		$data['prov_id'] = !empty($user_api['province']) ? $user_api['province'] : "";
		$data['city_id'] = !empty($user_api['city']) ? $user_api['city'] : "";
		}
		$data['groupid'] = !empty($data['openid']) ? 0 : $userconfig['user_email_auth'];
		$result = $this->validate('User.sns');
		if ($result->save($data)) {
			if ($isautologin) {
				session('user_auth_api',null);
				$this->autoLogin($this->data);
			}
			if(!empty($user_api['openid'])){
			$result->detail()->save($data);	
			$result->api()->save($data);
			}
				if($userconfig['user_register_score']){
					model('Score')->user_score($result->userid,1,intval($userconfig['user_register_score']));  
				}
				if($userconfig['user_register_vip']){
					model('Score')->user_reg_time($result->userid,intval($userconfig['user_register_vip']));  
				}				   
				if($result->userpid && $userconfig['user_register_score_uid']){
				    model('Score')->user_score($result->userpid,9,intval($userconfig['user_register_score_uid'])); 
			    }
			return $result;
		}else{
			if (!$this->getError()) {
				$this->error = "注册失败！";
			}
			return false;
		} 
	}	
	
    /**
	* 用户登录
	*/
	public function login($username = '', $password = '', $type = 1){
		$map = array();
		if (\think\Validate::is($username,'email')) {
			$type = 2;
		}elseif (preg_match("/^1[34578]{1}\d{9}$/",$username)) {
			$type = 3;
		}
		switch ($type) {
			case 1:
				$map['username'] = $username;
				break;
			case 2:
				$map['email'] = $username;
				break;
			case 3:
				$map['userid'] = $username;
				break;
			default:
				return 0; //参数错误
		}

		$user = $this->relation('detail,api')->where($map)->find();
		if($user['userid']){
			/* 验证用户密码 */
			if(md5(md5($password).$user['encrypt']) === $user['password']){
				if($user['islock']==1){
				return -3; //用户被禁用	
				}
				$user_api=session('user_auth_api');
				if(!empty($user_api['openid'])){
				$data['channel'] = !empty($user_api['channel']) ? $user_api['channel'] : "";
		        $data['openid'] = !empty($user_api['openid']) ? $user_api['openid'] : "";
		        $data['avatar'] = !empty($user_api['avatar']) ? $user_api['avatar'] : "";
			    $user->api()->save($data);
				session('user_auth_api',null);
				}
				$this->autoLogin($user); //更新用户登录信息
				return $user; //登录成功，返回用户ID
			} else {
				return -2; //用户密码错误
			}
		} else {
			return -1; //用户不存在
		}
	}	
	private function autoLogin($user){
		$userconfig=F('_data/userconfig_cache');
		/* 更新登录信息 */
		$data = array(
			'userid'             => $user['userid'],
			'loginnum'           => Db::raw('loginnum+1'),
			'lastdate' => time(),
			'lastip'   => get_client_ip(1),
		);
		db('user')->where('userid',$user['userid'])->update($data);
		$avatar=ps_getavatar($user['userid'],$user['pic'],$userinfo['api'][0]['avatar']);
		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'userid'  => $user['userid'],
			'username'  => $user['username'],
			'nickname'  => $user['nickname'],
			'useremail'  => $user['email'],
			'groupid'  => $user['groupid'],
			'avatar'  => $avatar['big'],
			'lastdate' => $user['lastdate'],
			'lastip' => $user['lastip'],
			'user_email_auth' => $userconfig['user_email_auth'],
		);
		if($userconfig['user_email_auth'] && $user['groupid']==1){
		    cookie('user_auth', null);
		    cookie('user_auth_sign', null);
		    session('user_auth', null);
		    session('user_auth_sign', null);
			session('user_auth_temp',$auth);//记录临时session方便重发邮件修改密码
		}
		else{
		//print_r(data_auth_sign($auth)) ;	
		cookie('user_auth', $auth);
		cookie('user_auth_sign', data_auth_sign($auth));
		session('user_auth', $auth);
		session('user_auth_sign', data_auth_sign($auth));
		session('user_auth_temp',$null);
		}
	}	
	
}
// +----------------------------------------------------------------------
// | ZanPianCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpian.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.feifeicms.cc>
// +----------------------------------------------------------------------